<?php

/**
 * 判断文件是否存在
 */
function check_file_exits($file_path)
{
    if (empty($file_path)) {
        return false;
    }

    $path = ROOT_PATH.'public/'.$file_path;

    return file_exists($path)?true:false;
}


/**
 * excel数据获取
 */
function xlsData($file,$column,$start = 2){
    if(!is_file($file)){
        echo "请选择文件";
        return [];
    }
    try{
        vendor("PHPExcel");
        vendor("PHPExcel.RichText");
        vendor("PHPExcel.IOFactory");
        $ext = strrchr($file,'.');
        if($ext == '.xls'){
            vendor("PHPExcel.Reader.Excel5");
            vendor("PHPExcel.Writer.Excel5");
            $excelReader = new \PHPExcel_Reader_Excel5();
        }else if($ext == '.xlsx'){
            vendor("PHPExcel.Reader.Excel2007");
            vendor("PHPExcel.Writer.Excel2007");
            $excelReader = new \PHPExcel_Reader_Excel2007();
        }

        $excel = $excelReader->load($file);

        $sheet = $excel->getSheet(0);

        $highestRow = $sheet->getHighestRow();

        $data = [];
        $column_num = count($column);

        for($j = $start; $j <= $highestRow; $j++ ) {
            $temp = [];
            for ($i = 0;$i < $column_num;$i++) {
                $cell = $sheet->getCellByColumnAndRow($i, $j);
                $value = $cell->getFormattedValue();
                if ($value instanceof \PHPExcel_RichText) {
                    $value = $value->__toString();
                }
                $temp[$column[$i]] = $value;
            }
            $data[] = $temp;
        }
    }catch (\Exception $exception){
        return [];
    }
    return $data;
}




/**
 * excel文件导出
 */
function getExcel($fileName, $headArr, $data)
{
    if (empty($fileName)) {
        exit;
    }
    $date = date("YmdHis", time());
    $fileName .= "_{$date}.xls";

    $objPHPExcel = new \PHPExcel();
    //第一列设置报表列头
    $key = ord("A");
    $key2 = ord("@");
    foreach ($headArr as $v) {
        if ($key > ord("Z")) {
            $key2 += 1;
            $key = ord("A");
            $colum = chr($key2) . chr($key);
            $objPHPExcel->setActiveSheetIndex(0)->getStyle(1)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            //字体加粗
            $objPHPExcel->getActiveSheet()->getStyle(1)->getFont()->setBold(true);
        } else {
            if ($key2 >= ord("A")) {
                $colum = chr($key2) . chr($key);
                $objPHPExcel->setActiveSheetIndex(0)->getStyle(1)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
                //字体加粗
                $objPHPExcel->getActiveSheet()->getStyle(1)->getFont()->setBold(true);
            } else {
                $colum = chr($key);
                $objPHPExcel->setActiveSheetIndex(0)->getStyle(1)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
                //字体加粗
                $objPHPExcel->getActiveSheet()->getStyle(1)->getFont()->setBold(true);
            }
        }
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $v);
        //设置水平居中
        $objPHPExcel->setActiveSheetIndex(0)->getStyle($colum)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        //设置垂直居中
        $objPHPExcel->getActiveSheet()->getStyle($colum)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
        // 设置个表格宽度
        $objPHPExcel->getActiveSheet()->getColumnDimension($colum)->setWidth(16);
        $key += 1;
    }
    $column = 2;
    $objActSheet = $objPHPExcel->getActiveSheet();

    foreach ($data as $key => $rows) {
        $span = ord("A");
        $span2 = ord("@");
        foreach ($rows as $keyName => $value) {
            if ($span > ord("Z")) {
                $span2 += 1;
                $span = ord("A");
                $j = chr($key2) . chr($span);
            } else {
                if ($span2 >= ord("A")) {
                    $j = chr($span2) . chr($span);
                } else {
                    $j = chr($span);
                }
            }
            $objActSheet->setCellValue($j . $column, $value);

            $span++;
        }
        $objActSheet->getRowDimension($key + 2)->setRowHeight(30);
        $column++;
    }

    $fileName = iconv("utf-8", "gb2312", $fileName);
    ob_end_clean();
    ob_start();
    $objPHPExcel->setActiveSheetIndex(0);

    header('Pragma: public');
    header('Content-Type:application/force-download');
    header('Content-Type: application/vnd.ms-excel');
    header("Content-Disposition: attachment;filename=\"$fileName\"");
    header('Cache-Control: max-age=0');
    $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
    $objWriter->save('php://output');
    exit;
}





/**
 * 树形结构
 * @return array
 */
function list_to_tree($list, $primary_key = 'id', $pid = 'parent_id', $child = 'children')
{
    $tree = [];
    if ($list instanceof \think\Collection) {
        $list = $list->toArray();
    }

    $level_column = array_column($list, 'level');

    $level = $level_column ? min($level_column) : 1;

    if (is_array($list)) {
        $refer = [];
        foreach ($list as $key => $data) {
            $refer[$data[$primary_key]] = &$list[$key];
        }
        foreach ($list as $key => $data) {
            $parentId = $data[$pid];
            if ($data['level'] == $level) {
                $tree[] =& $list[$key];
            } else {
                if (isset($refer[$parentId])) {
                    $parent = &$refer[$parentId];
                    $parent[$child][] =& $list[$key];
                }
            }
        }
    }
    return $tree;
}



/**
 * 发送短信接口
 */
function alsms($template,$mobile,$data){
    try{
        if(empty($template)){
            exception('短信模板为空');
        }
        if(empty($mobile)){
            exception('电话号码为空');
        }
        if(empty($data)){
            exception('短信内容为空');
        }

        if(is_array($mobile)){
            $mobile = implode(",",$mobile);
            $mobile = trim($mobile,",");
        }else{
            $mobile = trim($mobile);
        }

        $search = ["【","】","[","]"];
        $replace = ["","","",""];
        foreach($data as $key => $value){
            $data[$key] = str_replace($search,$replace,$value);
        }

        $sign = \think\Config::get('sms_tpl_id.sign_name');

        import('alsmsdemo.api_demo.SmsDemo',EXTEND_PATH);

        $result = SmsDemo::sendSms($sign,$template,$mobile,$data);

        if($result->Code == 'OK'){
            return ['code'=>'0','msg'=>'短信发送成功','data'=>[]];
        }else {
            exception($result->Message);
        }

    }catch (\Exception $exception) {
        return ['code'=>'1','msg'=>$exception->getMessage(),'data'=>[]];
    }
}



/**
 * 获取几个月后的日期
 */
function GetMonth($sign = "", $flag = false)
{

    $current_year = date("Y");
    $current_month = date("m");

    $current = mktime(0, 0, 0, $current_month + $sign, 1, $current_year);

    $first_day = date('Y-m-01', $current);
    $last_day = date('Y-m-d', strtotime(date('Y-m-01', $current) . ' +1 month -1 day'));
    if ($flag) {
        return date('Y-m', $current);
    }
    return ['0' => $first_day, '1' => $last_day];
}



/**
 * 根据url判断用户有没有权限
 */
function check_roles($url,$param = []){
    if(empty($url)){
        return false;
    }
    $roleId = session("user.role_id");
    if(empty($roleId)){
        return false;
    }
    if($roleId == 1){
        return true;
    }
    $menu = \app\common\model\Menu::getMenuByUrl($url,$param);
    if(empty($menu)){
        return false;
    }
    if(!$menu['is_show']){
        return false;
    }

    $menu_ids = \think\Db::name('user_role')->where(['id'=>$roleId])->column('menu_ids');
    $menu_arr=explode(',',$menu_ids[0]);
    if(in_array($menu['id'],$menu_arr)){
        return true;
    }
    return false;
}


function arrayNumericFormat($array){
    if(!is_array($array)){
        return stringNumericFormat($array);
    }
    foreach ($array as $k => &$v){
        if (is_array($v)){
            $v = arrayNumericFormat($v);
        }else{
            $v = stringNumericFormat($v);
        }
    }
    return $array;
}


/**
 *人民币大写
 */
function chinese_capital_amount($num)
{
    $c1 = "零壹贰叁肆伍陆柒捌玖";
    $c2 = "分角元拾佰仟万拾佰仟亿";

    $num = $num * 100;
    //精确到分
    $num = round($num, 0);
    if (strlen($num) > 10) {
        return "金额太大，请检查";
    }
    $i = 0;
    $c = "";
    while (1) {
        if ($i == 0) {
            $n = substr($num, strlen($num) - 1, 1);
        } else {
            $n = $num % 10;
        }
        $p1 = substr($c1, 3 * $n, 3);
        $p2 = substr($c2, 3 * $i, 3);
        if ($n != '0' || ($n == '0' && ($p2 == '亿' || $p2 == '万' || $p2 == '元'))) {
            $c = $p1 . $p2 . $c;
        } else {
            $c = $p1 . $c;
        }
        $i = $i + 1;
        $num = $num / 10;
        $num = (int)$num;
        if ($num == 0) {
            break;
        }
    }
    $j = 0;
    $slen = strlen($c);
    while ($j < $slen) {
        $m = substr($c, $j, 6);
        if ($m == '零元' || $m == '零万' || $m == '零亿' || $m == '零零') {
            $left = substr($c, 0, $j);
            $right = substr($c, $j + 3);
            $c = $left . $right;
            $j = $j - 3;
            $slen = $slen - 3;
        }
        $j = $j + 3;
    }
    if (substr($c, strlen($c) - 3, 3) == '零') {
        $c = substr($c, 0, strlen($c) - 3);
    }
    if (empty($c)) {
        return "零元整";
    } else {
        return $c . "整";
    }
}





function stringNumericFormat($value){
    if(is_numeric($value)){
        $value = round($value,2);
        if($value == (int)$value){
            $value = (int)$value;
        }
    }
    return $value;
}



